<template>
  <div class="app-container">
    <!--   inline 行内表单模式 input长度变短了-->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="queryParams.name"
                  placeholder="请输入单位名称"
                  clearable
                  @keyup.enter.native="handleQuery">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--  class="mb8" 调节表格和row之间的距离  -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['prod:unit:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="isNotSelectedOne"
                   @click="handleUpdate " v-hasPermi="['prod:unit:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="isNotSelectedAny"
                   @click="handleDelete" v-hasPermi="['prod:unit:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- plain是否朴素按钮-->
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['prod:unit:export']">导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
      <el-table-column width="55" align="center" type=selection>
      </el-table-column>
      <el-table-column align="center" prop="id" label="ID">
      </el-table-column>
      <el-table-column align="center" prop="name" label="单位名称">
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创造时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="修改时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['prod:unit:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['prod:unit:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 使用 ":page.sync" 可以将父组件中的属性与子组件中的属性进行双向绑定，并确保它们之间的状态保持同步-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getUnitList"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入计量单位名称" ref="dataFormNameRef"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getUnit, listUnit, deleteUnit, addUnit, updateUnit, checkExisting} from "@/api/prod/unit";


export default {
  name: "Unit",
  // dicts: ['sys_normal_disable'],


  data() {

    //自定义校验
    //GET /prod/unit/check/existing/:name/:id  url路径传参(/name/id) url?后面拼接参数(?ageNum=1&pageSize=10)
    let checkNameExisting = async (rule, value, callback) => {
      if (value === '' || value === undefined || value === null) {
        callback(new Error('请输入单位名称'));
        return;
      }
      let name = value;
      let pathParamsStr = name;
      let id = this.form.id;
      if (id !== undefined && id !== null && id !== 0) {
        pathParamsStr = pathParamsStr + "/" + id;
      } else {
        pathParamsStr = pathParamsStr + "/" + 0;
      }

      const res = await checkExisting(pathParamsStr)
      console.log(res);
      let isExisting = res.data;
      isExisting ? callback("已存在相同名称") : callback()
    }

    return {
      // 表格计量列表数据
      unitList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      total: 0,
      loading: true,
      //对话框的表单数据
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "单位名称不能为空", trigger: "blur"},
          {max: 2, message: "最大长度为2位字符", trigger: "blur"},
          {validator: checkNameExisting, trigger: "blur"}
        ],
      },
      //对话框动态标题
      title: "",
      //控制对话框的隐藏和显示
      open: false,
      // 选中数组
      ids: [],
      // 非单个禁用, 默认禁用
      isNotSelectedOne: true,
      // 非多个禁用
      isNotSelectedAny: true,
    };
  },
  created() {
    this.getUnitList()
  },
  methods: {
    //获取计量列表的数据
    getUnitList() {
      this.loading = true;
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //修改按钮操作
    handleUpdate(row) {
      this.reset()
      const unitId = row.id || this.ids
      getUnit(unitId).then(response => {
        this.form = response.data
        console.log(response.data)
        this.open = true;
        this.title = "修改单位";
        this.focus("dataFormNameRef");
      })
    },

    //删除功能
    handleDelete(row) {
      const unitId = row.id || this.ids
      this.$modal.confirm('是否确认删除ID为"' + unitId + '"的数据项？').then(function () {
        return deleteUnit(unitId);
      }).then(() => {
        this.getUnitList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('prod/unit/export', {
        ...this.queryParams
      }, `unit_${new Date().getTime()}.xlsx`)
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)

      this.isNotSelectedOne = selection.length != 1
      this.isNotSelectedAny = !selection.length
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        console.log(valid)
        if (valid) {
          if (this.form.id) {
            updateUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getUnitList();
            });
          } else {
            addUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getUnitList();
            });
          }
        }
      });
    },

    //新增功能
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '新增单位'
      this.focus("dataFormNameRef");
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined
      };
      this.resetForm("form");
    },

    //重置搜索框
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getUnitList();
    },
  }

}

</script>
